<?php
/*
	服务公司：沧州讯呗网络科技有限公司
	作者：sun
*/
namespace App\Http\Controllers\Web;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Repositories\PayRepository;
use App\Repositories\UsersRepository;
use App\Repositories\UserslogRepository;
use App\Repositories\OrderRepository;
use App\Repositories\OrderproductRepository;
use App\Repositories\PreferlogRepository;
use App\Repositories\RechargeRepository;
use App\Repositories\ProductRepository;
use Illuminate\Support\Facades\Response;
use App\Traits\BaseFun;
use App\Traits\FeiE;
use DaYin\didi;
use Zhifu\Juhe;
use Log;

class PayController extends Controller
{

    public function __construct(PayRepository $PayRepository,UsersRepository $UsersRepository,OrderRepository $OrderRepository,PreferlogRepository $PreferlogRepository,UserslogRepository $UserslogRepository,RechargeRepository $RechargeRepository,OrderproductRepository $OrderproductRepository,ProductRepository $ProductRepository)
    {
        $this->PayRepository = $PayRepository;
        $this->UsersRepository = $UsersRepository;
        $this->OrderRepository = $OrderRepository;
        $this->PreferlogRepository = $PreferlogRepository;
        $this->UserslogRepository = $UserslogRepository;
        $this->RechargeRepository = $RechargeRepository;
        $this->OrderproductRepository = $OrderproductRepository;
        $this->ProductRepository = $ProductRepository;
    }
    /**
     * 微信支付
     *
     * @return Response
     */
    public function pay(Request $request)
    {
        //1微信支付 2余额 3充值
        $data=[];
        if ($request->type==1 && $request->orderid) {
          $data['ordersn']=$this->OrderRepository->info(['id'=>$request->orderid])['order_sn'];
          $data['price']=$request->price;
          $openid=$this->UsersRepository->info(['id'=>$request->userId])['openid'];
          $pay = $this->PayRepository->pay($openid,$data);
        }elseif ($request->type==2 && $request->orderid) {
          $userBalance=$this->UsersRepository->info(['id'=>$request->userId])['balance'];
          $userB=$userBalance-$request->price;
          if ($userB>=0) {
            $orderInfo=$this->OrderRepository->info(['id'=>$request->orderid]);
            $userUpdate=$this->UsersRepository->update(['id'=>$request->userId,'balance'=>$userB]);
            $pay=$this->OrderRepository->update(['id'=>$request->orderid,'state'=>2]);
            $orderProduct=$this->OrderproductRepository->list(['orderid'=>$request->orderid]);//产品订单id

            foreach ($orderProduct as $key => $value) {
              $product=$this->ProductRepository->info(['id'=>$value['proid']]);
              // var_dump($product);die;
              $xiaoliang=$product['xiaoliang']+$value['num'];
              $this->ProductRepository->update(['id'=>$product['id'],'xiaoliang'=>$xiaoliang]);
            }
            $Preferlog=$this->PreferlogRepository->info(['preferid'=>$orderInfo['preferid'],'userid'=>$request->userId]);
            if ($Preferlog) {
              $this->PreferlogRepository->update(['id'=>$Preferlog['id'],'state'=>1]);
            }
            $this->UserslogRepository->create(['order_sn'=>$orderInfo['order_sn'],'price'=>$request->price,'userid'=>$request->userId,'type'=>2,'des'=>'平台余额消费']);
          }else{
            return BaseFun::jsonReturn(['state' => 2, 'data' => '', 'msg' => '余额不足!']);
          } 
        }else{
          $data['ordersn']='wx'.date('YmdHis', time()) . rand(1111, 9999);
          $data['price']=$request->price;
          $recharge=$this->RechargeRepository->info(['id'=>$request->rechargeId]);
          $this->UserslogRepository->create(['order_sn'=>$data['ordersn'],'price'=>$recharge['price']+$recharge['back_price'],'userid'=>$request->userId,'type'=>1,'state'=>2,'des'=>'充值'.$recharge['price'].'返现'.$recharge['back_price']]);
          $openid=$this->UsersRepository->info(['id'=>$request->userId])['openid'];
          $pay = $this->PayRepository->pay($openid,$data);
        }
        
         if ($pay) {
           $ArrDate = ['state' => 0, 'data' => $pay, 'token' => $request->input('token')];
        }else{
           $ArrDate = ['state' => 2, 'data' => $pay, 'msg' => '获取失败!']; 
        }
        return BaseFun::jsonReturn($ArrDate);
        // return Response::success(['pay' => $pay]);
    }

    //回调
    public function notify(Request $request)
    {
        return $this->PayRepository->notify();
    }
    //发送消息
    public function send(Request $request,$fromId)
    {
      $openid=$this->UsersRepository->info($request->userId)['openid'];
      return $this->PayRepository->send($fromId,$openid);
    }
    public function printMsg(Request $request)
    {
      
        $orderInfo=$this->OrderRepository->info(['id'=>$request->orderid]);
        $orderPro=$this->OrderproductRepository->list(['orderid'=>$request->orderid]);
        // $content ='<LOGO><BR>';
        $content = '<CB>毕成中餐厅</CB><BR>';
        $content .= '名称　　　　　 单价  数量 金额<BR>';
        $content .= '--------------------------------<BR>';
        // foreach ($orderPro as $key => $value) {
        //       $arr = str_split($value['name'], 20);
        //       $str = implode(' ', $arr);
        //       $contents=str_replace(" ","<BR>",$str);
        //       $content .= $contents.' '.$value['price'].'   '.$value['num'].'  '.$value['price']*$value['num'].'<BR>';
        // }
        $A=14;
        $B=6;
        $C=3;
        $D=6;
          foreach ($orderPro as $k5 => $v5) {
          $name = $v5['name'];
          $price = $v5['price'];
          $num = $v5['num'];
          $prices = $v5['price']*$v5['num'];
          $kw3 = '';
          $kw1 = '';
          $kw2 = '';
          $kw4 = '';
          $str = $name;
          $blankNum = $A;//名称控制为14个字节
          $lan = mb_strlen($str,'utf-8');
          $m = 0;
          $j=1;
          $blankNum++;
          $result = array();
          if(strlen($price) < $B){
                $k1 = $B - strlen($price);
                for($q=0;$q<$k1;$q++){
                      $kw1 .= ' ';
                }
                $price = $price.$kw1;
          }
          if(strlen($num) < $C){
                $k2 = $C - strlen($num);
                for($q=0;$q<$k2;$q++){
                      $kw2 .= ' ';
                }
                $num = $num.$kw2;
          }
          if(strlen($prices) < $D){
                $k3 = $D - strlen($prices);
                for($q=0;$q<$k3;$q++){
                      $kw4 .= ' ';
                }
                $prices = $prices.$kw4;
          }
          for ($i=0;$i<$lan;$i++){
            $new = mb_substr($str,$m,$j,'utf-8');
            $j++;
            if(mb_strwidth($new,'utf-8')<$blankNum) {
              if($m+$j>$lan) {
                $m = $m+$j;
                $tail = $new;
                $lenght = iconv("UTF-8", "GBK//IGNORE", $new);
                $k = $A - strlen($lenght);
                for($q=0;$q<$k;$q++){
                  $kw3 .= ' ';
                }
                if($m==$j){
                  $tail .= $kw3.' '.$price.' '.$num.' '.$prices;
                }else{
                  $tail .= $kw3.'<BR>';
                }
                break;
              }else{
                $next_new = mb_substr($str,$m,$j,'utf-8');
                if(mb_strwidth($next_new,'utf-8')<$blankNum) continue;
                else{
                  $m = $i+1;
                  $result[] = $new;
                  $j=1;
                }
              }
            }
          }
          $head = '';
          foreach ($result as $key=>$value) {
            if($key < 1){
              $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value);
              $v_lenght = strlen($v_lenght);
              if($v_lenght == 13) $value = $value." ";
              $head .= $value.' '.$price.' '.$num.' '.$prices;
            }else{
              $head .= $value.'<BR>';
            } 
          }
          $content .= $head.$tail;
          @$nums += $prices;
        }
        $content .= '--------------------------------<BR>';
        $content .= '备注：'.$orderInfo['bz'].'<BR>';
        $content .= '合计：'.$orderInfo['price'].'元<BR>';
        $content .= '送货地点：'.$orderInfo['street'].$orderInfo['address'].'<BR>';
        $content .= '联系人：'.$orderInfo['username'].'<BR>';
        $content .= '联系电话：'.$orderInfo['mobile'].'<BR>';
        $content .= '订餐时间：'.date('Y-m-d H:i:s',time()).'<BR>';
        // $content .= '<QR>http://www.feieyun.com</QR>';
        $dayin=new didi();
        $dayin->dingdan(930519173,$content,1);
    }
    public function payJuhe(Request $request)
    {
      $data=[];
      if ($request->type==1 && $request->orderid) {
      $data['ordersn']=$this->OrderRepository->info(['id'=>$request->orderid])['order_sn'];
      $data['price']=$request->price;
      $openid=$this->UsersRepository->info(['id'=>$request->userId])['openid'];
       $zhifu=new Juhe();
       $pay=$zhifu->pay($openid,$data);
      }elseif ($request->type==2 && $request->orderid) {
          $userBalance=$this->UsersRepository->info(['id'=>$request->userId])['balance'];
          $userB=$userBalance-$request->price;
          if ($userB>0) {
            $orderInfo=$this->OrderRepository->info(['id'=>$request->orderid]);
            $userUpdate=$this->UsersRepository->update(['id'=>$request->userId,'balance'=>$userB]);
            $pay=$this->OrderRepository->update(['id'=>$request->orderid,'state'=>2]);
            $orderProduct=$this->OrderproductRepository->list(['orderid'=>$request->orderid]);//产品订单id
            foreach ($orderProduct as $key => $value) {
              if ($value['proid']) {            
              $product=$this->ProductRepository->info(['id'=>$value['proid']]);
              $xiaoliang=$product['xiaoliang']+$value['num'];
              $this->ProductRepository->update(['id'=>$product['id'],'xiaoliang'=>$xiaoliang]);
              }
            }
            $Preferlog=$this->PreferlogRepository->info(['preferid'=>$orderInfo['preferid'],'userid'=>$request->userId]);
            if ($Preferlog) {
              $this->PreferlogRepository->update(['id'=>$Preferlog['id'],'state'=>1]);
            }
            $this->UserslogRepository->create(['order_sn'=>$orderInfo['order_sn'],'price'=>$request->price,'userid'=>$request->userId,'type'=>2,'des'=>'平台余额消费']);
          }else{
            return BaseFun::jsonReturn(['state' => 2, 'data' => '', 'msg' => '余额不足!']);
          } 
        }else{
          $data['ordersn']='wx'.date('YmdHis', time()) . rand(1111, 9999);
          $data['price']=$request->price;
          $recharge=$this->RechargeRepository->info(['id'=>$request->rechargeId]);
          $this->UserslogRepository->create(['order_sn'=>$data['ordersn'],'price'=>$recharge['price']+$recharge['back_price'],'userid'=>$request->userId,'type'=>1,'state'=>2,'des'=>'充值'.$recharge['price'].'返现'.$recharge['back_price']]);
          $openid=$this->UsersRepository->info(['id'=>$request->userId])['openid'];
          $zhifu=new Juhe();
          $pay=$zhifu->pay($openid,$data);
        }
    if ($pay) {
           $ArrDate = ['state' => 0, 'data' => $pay, 'token' => $request->input('token')];
        }else{
           $ArrDate = ['state' => 2, 'data' => $pay, 'msg' => '获取失败!']; 
        }
        return BaseFun::jsonReturn($ArrDate);
    }
    public function payNotify(Request $request)
    {
     
       $zhifu=new Juhe();
       $zhifu->notify();
       echo 'SUCCESS';
    }
}